include(CMakeParseArguments)

# add_test_bundle(<name>    # Bundle name (e.g. fr.osgi.test.alone)
#   VERSION version         # Bundle version (3 numbers, dot-separated, e.g. 1.2.10)
#   SOURCES files...        # Bundle source files.
# )
#
# Test bundles are built thanks to this function.
#
function(add_test_bundle BUNDLE_NAME)

    set(Arguments VERSION)
    set(MultiArguments SOURCES)
    cmake_parse_arguments(BUNDLE "" "${Arguments}" "${MultiArguments}" ${ARGN})

    set(LIBRARY     ${BUNDLE_NAME})
    set(BUNDLE      ${BUNDLE_NAME}_${BUNDLE_VERSION}.bndl)
    set(BUNDLESPEC  ${BUNDLE_NAME}_${BUNDLE_VERSION}.bundlespec)

    get_filename_component(DIR ${CMAKE_CURRENT_BINARY_DIR} NAME)
    if(NOT TARGET ${DIR}.${LIBRARY})
        add_library(${DIR}.${LIBRARY} SHARED EXCLUDE_FROM_ALL ${BUNDLE_SOURCES})
        set_target_properties(${DIR}.${LIBRARY} PROPERTIES PREFIX "" OUTPUT_NAME ${LIBRARY})
        target_link_libraries(${DIR}.${LIBRARY} OSGi++)
    endif()

    # Automatically adds properties file, if found (it may be versioned).
    if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/${BUNDLE_NAME}.properties)
        set(OTHER_FILES -f${BUNDLE_NAME}.properties=${CMAKE_CURRENT_SOURCE_DIR}/${BUNDLE_NAME}.properties)
    elseif(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/${BUNDLE_NAME}_${BUNDLE_VERSION}.properties)
        set(OTHER_FILES -f${BUNDLE_NAME}.properties=${CMAKE_CURRENT_SOURCE_DIR}/${BUNDLE_NAME}_${BUNDLE_VERSION}.properties)
    endif()
    # Automatically adds extension file, if found
    if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/${BUNDLE_NAME}.extensions.xml)
        set(OTHER_FILES ${OTHER_FILES} -fextensions.xml=${CMAKE_CURRENT_SOURCE_DIR}/${BUNDLE_NAME}.extensions.xml)
    endif()

    configure_file(${CMAKE_CURRENT_SOURCE_DIR}/${BUNDLESPEC} ${CMAKE_CURRENT_BINARY_DIR}/${BUNDLESPEC})

    add_custom_command(OUTPUT ${OSGi_BINARY_DIR}/bundles/${BUNDLE}
        COMMAND osgi-packager
                -I${CMAKE_CURRENT_BINARY_DIR}               # Uses configured files first.
                -I${CMAKE_CURRENT_SOURCE_DIR}
                -o ${OSGi_BINARY_DIR}/bundles/${BUNDLE}
                ${OTHER_FILES}
                ${CMAKE_CURRENT_BINARY_DIR}/${BUNDLESPEC}   # Bundlespec file is the last argument.
        DEPENDS ${DIR}.${LIBRARY}
                osgi-packager
                ${CMAKE_CURRENT_BINARY_DIR}/${BUNDLESPEC}
    )

    add_custom_target(${BUNDLE} DEPENDS ${OSGi_BINARY_DIR}/bundles/${BUNDLE})
    add_dependencies(valid ${BUNDLE})

endfunction()

add_subdirectory(loading)
add_subdirectory(dependency)
add_subdirectory(xp)
